package com.example.acamp.dip;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

public class PicListActivity extends Activity
        implements PicListFragment.Callbacks {

    private boolean mTwoPane;
    private boolean mExternalSaveLocation;

	private static final String SP_IS_EXTERNAL_SAVE = "EX_S";
    
    public boolean isExternalSaveLocation() {
    	return mExternalSaveLocation;
    }
    
    public void toggleSaveLocation() {
    	mExternalSaveLocation = !mExternalSaveLocation;

		// Each time we toggle the save location, save out to shared preferences
		SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
		sp.edit()
			.putBoolean(SP_IS_EXTERNAL_SAVE, mExternalSaveLocation)
			.commit();
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.one_pane);
        
        // get our preference
    	SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
    	mExternalSaveLocation = sp.getBoolean(SP_IS_EXTERNAL_SAVE, true);
    	
        // if the savedInstanceState is not null, we don't initialize
        // the fragment
        if ( null == savedInstanceState ) {
	        PicListFragment listFragment = new PicListFragment();
	        getFragmentManager().beginTransaction()
	        	.replace(R.id.first_pane, listFragment)
	        	.commit();
        }
        
        if (findViewById(R.id.second_pane) != null) {
            mTwoPane = true;
        }
    }

    @Override
    public void onItemSelected(String urlString, String itemName) {
        if (mTwoPane) {
            Bundle arguments = new Bundle();
            arguments.putString(PicDetailFragment.ARG_ITEM_URL, urlString);
            arguments.putString(PicDetailFragment.ARG_ITEM_NAME, itemName);
            PicDetailFragment fragment = new PicDetailFragment();
            fragment.setArguments(arguments);
            getFragmentManager().beginTransaction()
                    .replace(R.id.second_pane, fragment)
                    .commit();

        } else {
            Bundle arguments = new Bundle();
            arguments.putString(PicDetailFragment.ARG_ITEM_URL, urlString);
            arguments.putString(PicDetailFragment.ARG_ITEM_NAME, itemName);
            PicDetailFragment fragment = new PicDetailFragment();
            fragment.setArguments(arguments);
            getFragmentManager().beginTransaction()
                    .replace(R.id.first_pane, fragment)
                    .addToBackStack("Detail")
                    .commit();        	
        }
    }
}
